package com.unionftech.content_login.api.mock

import android.text.TextUtils
import com.google.gson.Gson
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SpUtils
import com.unionftech.content_login.api.mock.bean.MockAccountInfo
import com.unionftech.content_login.api.mock.bean.UserInfo
import retrofit2.mock.BehaviorDelegate

class MockLoginApi(private val delegate: BehaviorDelegate<LoginMockApi>) : LoginMockApi {
    private val gson by lazy { Gson() }
    override suspend fun requestLogin(
        phone: String,
        areaCode: String,
        email: String,
        pwd: String,
        loginType: Int
    ): ResponseResult<UserInfo> {
        val result = if (loginType == MockAccountInfo.TYPE_EMAIL) {
            loginByEmail(email, pwd)
        } else {
            loginByPhone(phone, pwd, areaCode)
        }
        return delegate.returningResponse(result)
            .requestLogin(phone, areaCode, email, pwd, loginType)
    }

    override suspend fun requestForgotPassword(
        phone: String,
        areaCode: String,
        email: String,
        pwd: String,
        type: Int
    ): ResponseResult<String> {
        val result = if (type == MockAccountInfo.TYPE_EMAIL) {
            resetPasswordByEmail(email, pwd)
        } else {
            resetPasswordByPhone(phone, areaCode, pwd)
        }
        return delegate.returningResponse(result)
            .requestForgotPassword(phone, areaCode, email, pwd, type)
    }

    private fun resetPasswordByEmail(
        email: String,
        pwd: String
    ): ResponseResult<String?> {
        var isExist = false
        val userJsonSet = SpUtils.getInstance().getStringSet(MockServer.MOCK_EMAIL_ACCOUNT_LIST)
        if (userJsonSet != null && userJsonSet.isNotEmpty()) {
            val iterator = userJsonSet.iterator()
            var newUserJson: String? = null
            while (iterator.hasNext()) {
                val userJson = iterator.next()
                val info = gson.fromJson(userJson, MockAccountInfo::class.java)
                if (info.email == email && !TextUtils.isEmpty(pwd)) {
                    isExist = true
                    iterator.remove()
                    val copyInfo = info.copy(password = pwd)
                    newUserJson = gson.toJson(copyInfo)
                    break
                }
            }
            userJsonSet.add(newUserJson)
            LogUtils.d("resetPasswordByEmail last set ----->${userJsonSet.toString()}")
            SpUtils.getInstance().put(MockServer.MOCK_EMAIL_ACCOUNT_LIST, userJsonSet)
        }
        return if (isExist) {
            ResponseResult.buildSuccess("reset password success")
        } else {
            ResponseResult.buildFail("reset password failed")
        }
    }

    private fun resetPasswordByPhone(
        phone: String,
        areaCode: String,
        pwd: String
    ): ResponseResult<String?> {
        var isExist = false
        val userJsonSet = SpUtils.getInstance().getStringSet(MockServer.MOCK_PHONE_ACCOUNT_LIST)
        if (userJsonSet != null && userJsonSet.isNotEmpty()) {
            val iterator = userJsonSet.iterator()
            var newUserJson: String? = null
            while (iterator.hasNext()) {
                val userJson = iterator.next()
                val info = gson.fromJson(userJson, MockAccountInfo::class.java)
                if (info.phone == phone && info.areaCode == areaCode && !TextUtils.isEmpty(pwd)) {
                    isExist = true
                    iterator.remove()
                    val copyInfo = info.copy(password = pwd)
                    newUserJson = gson.toJson(copyInfo)
                    LogUtils.d("newUserJson---->${newUserJson}")
                    break
                }
            }
            userJsonSet.add(newUserJson)
            LogUtils.d("resetPasswordByPhone last set ----->${userJsonSet.toString()}")
            SpUtils.getInstance().put(MockServer.MOCK_PHONE_ACCOUNT_LIST, userJsonSet)
        }
        return if (isExist) {
            ResponseResult.buildSuccess("reset password success")
        } else {
            ResponseResult.buildFail("reset password failed")
        }
    }

    private fun loginByPhone(
        phone: String,
        pwd: String,
        areaCode: String
    ): ResponseResult<UserInfo?> {
        val set = SpUtils.getInstance().getStringSet(MockServer.MOCK_PHONE_ACCOUNT_LIST)
        LogUtils.d("local user data by phone ----> $set")
        if (set != null && set.isNotEmpty()) {
            for (json in set) {
                val info = gson.fromJson(json, MockAccountInfo::class.java)
                if (info.phone == phone && info.password == pwd && info.areaCode == areaCode) {
                    val userInfo = UserInfo("${info.firstName} ${info.lastName}", "")
                    return ResponseResult.buildSuccess(userInfo)
                }
            }
        }
        val result: ResponseResult<UserInfo?> = ResponseResult.buildFail(null)
        result.msg = "login failed"
        return result
    }

    private fun loginByEmail(
        email: String,
        pwd: String
    ): ResponseResult<UserInfo?> {
        val set = SpUtils.getInstance().getStringSet(MockServer.MOCK_EMAIL_ACCOUNT_LIST)
        LogUtils.d("local user data by email ----> $set")
        if (set != null && set.isNotEmpty()) {
            for (json in set) {
                val info = gson.fromJson(json, MockAccountInfo::class.java)
                if (info.email == email && info.password == pwd) {
                    val userInfo = UserInfo("${info.firstName} ${info.lastName}", "")
                    return ResponseResult.buildSuccess(userInfo)
                }
            }
        }
        val result: ResponseResult<UserInfo?> = ResponseResult.buildFail(null)
        result.msg = "login failed"
        return result
    }
}